<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="uage" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn(uname, uage, sex)">添加/修改</button>
    </div>
    <div>
      <table
        v-show="list.length > 0"
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="obj in list" :key="obj.id">
          <td>{{ obj.id }}</td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.gender }}</td>
          <td>
            <button @click="delFn(obj.id)">删除</button>
            <button @click="writeFn(obj.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          name: "Tom",
          age: 19,
          gender: "男",
        },
        {
          id: 2,
          name: "Jone",
          age: 21,
          gender: "女",
        },
      ],
      isShow: true,
      uname: "",
      uage: 0,
      sex: "",
      btn: false,
      ind: "",
    };
  },
  methods: {
    addFn(name, age, gender) {
      if (this.btn === false) {
        if (name === "" || age <= 0 || gender === "") {
          alert("添加不能为空，请重新输入");
        } else {
          this.list.push({
            id: this.list.length + 1,
            name: this.uname,
            age: this.uage,
            gender: this.sex,
          });
          this.uname = "";
          this.uage = 0;
          this.sex = "";
        }
      } else {
        // console.log(this.list[this.ind].id - 1);
        // console.log(this.list[this.list[this.ind].id - 1]);
        this.list.splice(this.list[this.ind].id, 0, {
          id: this.list[this.ind].id,
          name: this.uname,
          age: this.uage,
          gender: this.sex,
        });
        this.list.splice(this.list[this.ind].id - 1, 1);
        this.uname = "";
        this.uage = 0;
        this.sex = "";
        this.btn = false;
      }
    },
    writeFn(index) {
      this.uname =
        this.list[this.list.findIndex((item) => item.id === index)].name;
      this.uage =
        this.list[this.list.findIndex((item) => item.id === index)].age;
      this.sex =
        this.list[this.list.findIndex((item) => item.id === index)].gender;
      this.btn = true;
      this.ind = this.list.findIndex((item) => item.id === index);
    },
    delFn(index) {
      let num = this.list.findIndex((item) => item.id === index);
      this.list.splice(num, 1);
    },
  },
};
</script>
